<template>
  <p-card :bordered="false" class="peopleInfo">
    <!-- 查询区域 -->
    <div
      class="table-page-search-wrapper"
      v-if="queryParamArr && queryParamArr.length > 0"
    >
      <!-- 回车事件 -->
      <p-form layout="inline" @keyup.enter.native="searchQuery">
        <p-row :gutter="24">
          <p-col
            :xl="6"
            :lg="7"
            :md="8"
            :sm="24"
            v-for="(item, index) in queryParamArr"
            :key="index"
          >
            <p-form-item :label="item.label">
              <p-input
                v-show="!isItemSelect"
                :placeholder="item.placeholder"
                v-model="item.value"
              ></p-input>
              <p-select
                v-show="isItemSelect"
                v-model="item.value"
                :placeholder="item.placeholder"
                :filter-option="filterOption"
              >
                <p-select-option
                  v-for="(item, key) in selectTypeKeys"
                  :key="key"
                  :value="item"
                >
                  {{ item }}
                </p-select-option>
              </p-select>
            </p-form-item>
          </p-col>
          <p-col :xl="6" :lg="7" :md="8" :sm="24">
            <span
              style="float: left; overflow: hidden"
              class="table-page-search-submitButtons"
            >
              <!-- 点击事件 -->
              <p-button type="primary" @click="searchQuery" icon="search"
                >查询</p-button
              >
              <p-button
                type="primary"
                @click="searchReset"
                icon="reload"
                style="margin-left: 8px"
                >重置</p-button
              >
            </span>
          </p-col>
        </p-row>
      </p-form>
    </div>

    <slot name="btn"></slot>

    <!-- 高级查询区域  要有他的长度大于0 ref  高级查询的方法-->
    <j-super-query
      v-if="superQueryFieldList && superQueryFieldList.length > 0"
      :fieldList="superQueryFieldList"
      ref="superQueryModal"
      @handleSuperQuery="handleSuperQuery"
      style="padding-bottom: 10px; margin-right: 10px"
    ></j-super-query>

    <p-button
      type="primary"
      v-if="isShowDeleteBatch"
      :disabled="selectedRowKeys.length == 0"
      @click="handleDeleteBatch"
      >批量删除</p-button
    >

    <!-- table区域-begin -->
    <div class="peopleInfo-table">
      <div
        v-if="isShowToolBar"
        class="ant-alert ant-alert-info"
        style="margin-bottom: 16px"
      >
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>

        <span style="float: right">
          <a @click="handleExportXls('关键字段信息')">
            <p-icon type="download" />导出
          </a>
          <p-divider type="vertical" />
          <p-upload
            name="file"
            :showUploadList="false"
            :multiple="false"
            :headers="tokenHeader"
            :action="importExcelUrl"
            @change="handleImportExcel"
          >
            <a> <p-icon type="import" />导入 </a>
          </p-upload>
          <p-divider type="vertical" />
          <a @click="loadData()"> <p-icon type="sync" />刷新 </a>
          <p-divider type="vertical" />
          <p-popover
            title="自定义列"
            trigger="click"
            placement="leftBottom"
            :overlay-style="getWidth"
          >
            <template slot="content">
              <p-checkbox-group
                @change="onColSettingsChange"
                v-model="settingColumns"
                :defaultValue="settingColumns"
              >
                <p-row>
                  <template v-for="(item, index) in defColumns">
                    <template
                      v-if="
                        item.key != 'rowIndex' && item.dataIndex != 'action'
                      "
                    >
                      <p-col :span="12">
                        <p-checkbox :value="item.dataIndex">{{
                          item.title
                        }}</p-checkbox>
                      </p-col>
                    </template>
                  </template>
                </p-row>
              </p-checkbox-group>
            </template>
            <a> <p-icon type="setting" />自定义列 </a>
          </p-popover>
        </span>
      </div>

      <!-- :scroll="tableScroll" -->
      <!-- :scroll="{ x: 1000, y: 300 }" -->

      <p-table
        ref="table"
        size="middle"
        bordered
        :rowKey="rowKey"
        :columns="columns"
        :scroll="tableScroll"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="
          isShowRowSelection
            ? {
                selectedRowKeys: selectedRowKeys,
                onChange: onSelectChange,
                type: rowSelectionType,
                getCheckboxProps,
              }
            : null
        "
        @change="handleTableChange"
      >
        <template
          v-if="isUseStatusTemp"
          slot="status"
          slot-scope="text, record"
        >
          <p-switch
            size="small"
            v-model="record.status"
            @change="onSwitchChange(record)"
          />
        </template>

        <!-- <template  v-for="(val, index) in tempArr" :key="index" :slot="val" slot-scope="text, record">
          <div>
            
          </div>
        </template> -->

        <div
          slot-scope="text, record"
          v-for="(item, index) in tempArr"
          :key="index"
          :slot="item"
        >
          <slot :name="item" :record="record"></slot>
        </div>

        <template slot="empsex" slot-scope="text">
          <span v-if="text == 2">女</span>
          <span v-else-if="text == 1">男</span>
          <span v-else> -- </span>
        </template>

        <template slot="url" slot-scope="text, record">
          <a :href="text" target="_blank">下载附件</a>
        </template>
        <template slot="changeLineTimes" slot-scope="text">
          <span>>{{ text }}</span>
        </template>
        <template slot="hasStimulate" slot-scope="text">
          <span v-if="text == 1">是</span>
          <span v-else-if="text == 0">否</span>
        </template>
        <template slot="isArrival" slot-scope="text">
          <span v-if="text == 1">是</span>
          <span v-else-if="text == 0">否</span>
        </template>

        <template slot="status" slot-scope="text">
          <p-switch :checked="text == 1 ? true : false" disabled />
        </template>

        <template slot="exceptionType" slot-scope="text">
          {{ exceptionTypes[text] }}
        </template>

        <template slot="action" slot-scope="text, record">
          <slot name="action" :record="record">
            <a @click="handleEdit(record)">编辑</a>
            <p-divider type="vertical" v-show="isShowDelete" />
            <p-dropdown v-show="isShowDelete">
              <a class="ant-dropdown-link">
                更多
                <p-icon type="down" />
              </a>
              <p-menu slot="overlay">
                <p-menu-item>
                  <p-popconfirm
                    title="确定删除吗?"
                    @confirm="() => handleDelete(record.id)"
                  >
                    <a>删除</a>
                  </p-popconfirm>
                </p-menu-item>
              </p-menu>
            </p-dropdown>
          </slot>
        </template>
      </p-table>
    </div>
  </p-card>
</template>

<script type="text/javascript">
import JSuperQuery from '@/components/jeecg/JSuperQuery.vue'
import { postAction, getAction, deleteAction, putAction } from '@/api/manage'
import { filterObj, getDictItemsArr } from '@/utils/util'

export default {
  name: 'RenderTable',
  props: {
    // 高级查询
    superQueryFieldList: {
      type: Array,
      // required: true,
      default: [],
    },
    // 选择款类型
    rowSelectionType: {
      type: String,
      // required: true,
      default: '',
    },
    isItemSelect: {
      type: Boolean,
      default: false,
    },
    // 是否有选择框
    isShowRowSelection: {
      type: Boolean,
      default: false,
    },
    // 默认的查询参数
    defaultQueryParam: {
      type: Object,
      // required: true,
      default: {},
    },
    // 查询的数组
    queryParamArr: {
      type: Array,
      default: [],
    },
    // 列定义
    defColumns: {
      type: Array,
    },
    // 请求接口地址
    url: {
      type: Object,
    },
    // 获取列表时默认的请求参数
    defaultParams: {
      type: Object,
      default: {},
    },
    // 是否显示工具栏
    isShowToolBar: {
      type: Boolean,
      default: true,
    },
    // 是否显示批量删除
    isShowDeleteBatch: {
      type: Boolean,
      default: false,
    },
    // 是否显示批量删除
    isShowDelete: {
      type: Boolean,
      default: true,
    },
    // 是否使用状态模板
    isUseStatusTemp: {
      type: true,
      default: false,
    },
    // 模板列表
    tempArr: {
      type: Array,
      default: [],
    },
    // 假期分类下拉列表
    selectTypeKeys: {
      type: Object,
      default: {},
    },
    // rowKey
    rowKey: {
      type: String,
      default: 'id',
    },
    getCheckboxProps: {
      type: Function,
    },
  },
  data() {
    return {
      exceptionTypes: {},
      queryParam: {},
      originQueryParam: {},
      originQueryParamArr: [],
      selectedRowKeys: [],
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading: false,
      /* table选中keys */
      selectedRowKeys: [],
      /* table选中records */
      selectionRows: [],
      /* 查询折叠 */
      toggleSearchStatus: false,
      /* 高级查询条件生效状态 */
      superQueryFlag: false,
      /* 高级查询条件 */
      superQueryParams: '',
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      dataSource: [],
      // 表头
      columns: [],
      //列设置
      settingColumns: [],
    }
  },
  computed: {
    tableScroll() {
      if (this.columns.length > 13) {
        const index = [0, 1, 2, this.columns.length - 1]
        let total = 0
        index.forEach((i) => {
          total += this.columns[i].width
        })
        return { x: this.columns.length * 150 - total }
      }
    },
  },

  watch: {
    // 监听上面数组的变化 他变你变,具有响应式$set
    queryParamArr: {
      handler(newName, oldName) {
        newName.forEach((ele) => {
          this.$set(this.queryParam, ele.key, ele.value)
        })
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    this.originQueryParamArr = JSON.parse(JSON.stringify(this.queryParamArr))
    this.initColumns()
    this.setDefColumns()
    this.loadData(1)
    this.getAjaxGetDictItems()
  },
  methods: {
    // 获取数字字典
    getAjaxGetDictItems() {
      const arr = [{ code: 'mes_hr_us_exception_type', key: 'exceptionTypes' }]
      getDictItemsArr(this, arr)
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      )
    },
    // 初始化 tabe的Columns
    initColumns() {
      let allSettingColumns = []
      this.defColumns.forEach(function (item, i, array) {
        allSettingColumns.push(item.dataIndex)
      })
      this.settingColumns = allSettingColumns
      this.columns = this.defColumns
    },

    //列设置更改事件
    onColSettingsChange(checkedValues) {
      this.settingColumns = checkedValues
      const cols = this.defColumns.filter((item) => {
        if (item.key == 'rowIndex' || item.dataIndex == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true
        }
        return false
      })
      this.columns = cols
    },

    // table 的分页事件
    handleTableChange(pagination, filters, sorter) {
      // 分页、排序、筛选变化时触发
      // TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
      }
      //筛选 多选
      Object.keys(filters).map((key) => {
        let k = key
        let data = []
        filters[k].forEach((item, index) => {
          data.push(item)
        })
        //表头筛选表头带的value值是字典的value，接口筛选的时候需要的是字典的key 这边把表头携带的_deicText  默认去掉
        if (k.indexOf('_dictText') > -1) {
          k = k.replace('_dictText', '')
        }
        this.queryParam[k] = data.toString('')
      })
      this.ipagination = pagination
      this.loadData()
    },
    // 设置table的 columns
    setDefColumns() {
      if (this.columns.length > 13) {
        let arrLength = this.columns.length - 1
        this.columns.forEach((item, index) => {
          if (!item.width) {
            item['width'] = 150
          }
        })
        this.columns[arrLength]['fixed'] = 'right'
        this.columns[0]['fixed'] = 'left'
        this.columns[1]['fixed'] = 'left'
        this.columns[2]['fixed'] = 'left'
      }
    },
    // 查询 默认加载第一页
    searchQuery() {
      this.loadData(1)
    },
    // 重置查询   上面查询的数组value值都清空 默认加载第一页
    searchReset() {
      this.queryParamArr.forEach((item) => {
        item.value = ''
      })
      this.$nextTick(() => {
        this.loadData(1)
      })
    },
    //高级查询方法 如果没有arg就高级查询的状态为false 查询条件为空 反之为true 赋值给高级查询条件  调用查询列表
    handleSuperQuery(arg) {
      console.log(arg)
      if (!arg) {
        this.superQueryParams = ''
        this.superQueryFlag = false
      } else {
        this.superQueryFlag = true
        this.superQueryParams = JSON.stringify(arg)
      }
      this.loadData()
    },
    // 获取查询条件
    getQueryParams() {
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
      }
      var param = Object.assign(sqp, this.queryParam, this.defaultQueryParam)
      param.pageNo = this.ipagination.current
      param.limit = this.ipagination.pageSize
      return filterObj(param)
    },
    // table选中改变
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
      this.$emit('onSelectChange', selectionRows)
    },
    // 清除table选中  table选中清空 
    onClearSelected() {
      this.onSelectChange([], [])
      this.$emit('onClearSelected', [])
    },
    // 查询列表 加载第一页的数据  清除页面被选中的
    loadData(pageIndex) {
      if (pageIndex === 1) {
        this.ipagination.current = 1
      }
      this.onClearSelected()
      let params = this.getQueryParams() //查询条件
      Object.assign(params, this.defaultParams)
      this.loading = true
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.data.records.map((ele) => {
            if (
              ele.status &&
              (ele.status == 0 || ele.status == 1) &&
              this.isUseStatusTemp
            ) {
              ele.status = ele.stats == 0 ? false : true
            }
            return ele
          })
          this.ipagination.total = res.data.total
        }
        if (res.code === 510) {
          this.$message.warning(res.msg)
        }
        this.$nextTick(() => {
          this.loading = false
        })
      })
    },
    // 编辑
    handleEdit(record) {
      this.$emit('handleEdit', record)
    },

    // 提交审批
    handleSubmit(record) {
      this.$emit('handleSubmit', record)
    },

    // 删除
    handleDelete(id) {
      this.$emit('handleDelete', id)
      deleteAction(this.url.delete + '/' + id).then((res) => {
        if (res.success) {
          this.loadData()
        }
      })
    },

    // 批量删除 将所有的数组转换成字符串 接口请求,刷新
    handleDeleteBatch() {
      const idStr = this.selectedRowKeys.join(',')
      deleteAction(this.url.delete + '/' + idStr).then((res) => {
        if (res.success) {
          this.loadData()
        }
      })
    },

    // 修改状态
    onSwitchChange(record) {
      console.log(record)
      const params = {
        status: record.status ? 1 : 0,
        id: record.id,
      }
      postAction(this.url.editStatus, params).then((res) => {
        if (res.success) {
          this.$message.success('修改状态成功!')
        } else {
          this.$message.error('修改状态失败!')
          record.status = !record.status
        }
      })
    },
  },
  components: {
    JSuperQuery,
  },
}
</script>

<style lang="less" scoped>
</style>


